package org.zfes.snowier.common.monitor.mysql;

import java.util.Optional;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;

public class MonitorDataContainer {
	private static final Long queueCapacity= 10000*2L; 
	public static MonitorDataContainer dataContainer;
	
	private static ConcurrentLinkedQueue<MonitorData> concurrentLinkedQueue=new ConcurrentLinkedQueue<MonitorData>();
	private static AtomicLong queueSize=new AtomicLong(0); 
	
	
	private MonitorDataContainer() {}

	public static MonitorDataContainer getInstance() {
	        if (dataContainer == null) {
	            synchronized (MonitorDataContainer.class) {
	            	if (dataContainer == null) {
	            		dataContainer = new MonitorDataContainer();
	                }
	            }
	        }
	     return dataContainer;
	 }
	
	public  boolean add(MonitorData obj) {
		//logger.debug("--add:  "+obj);
		//容量超了直接舍弃头部数据
		if(queueSize.get()>= queueCapacity) {
			concurrentLinkedQueue.poll();
		}
		queueSize.incrementAndGet();
		return concurrentLinkedQueue.add(obj);
	}
	 
	public  Optional<MonitorData> poll()  {
		if(queueSize.get()==0) {
			return Optional.empty();
		}
		queueSize.getAndDecrement();
		return Optional.ofNullable(concurrentLinkedQueue.poll());
	}
	
	public  long size()  {
		return queueSize.get();
	}
	
	public  boolean isEmpty()  {
		return queueSize.get()==0L;
	}
}
